import {
	HTTP_REQUEST_URL,
	HEADER,
	TOKENNAME,
	HEADERPARAMS
} from '@/config/app';
import store from '../store';
import code from '../uni_modules/uview-ui/libs/config/props/code';
/**
 * 发送请求
 * noAuth 不需要授权
 */

function baseRequest(url, method, data, {
	noAuth = false
}, params) {
	let Url = HTTP_REQUEST_URL,
		header = HEADER
	if (params != undefined) {
		header = HEADERPARAMS;
	}
	let token = uni.getStorageSync("TOKEN")
	if (!noAuth) {
		if (!token) {
			store.commit("LOGOUT");
			// uni.showToast({
			// 	title: "未登录或授权已过期请重新登录",
			// 	icon: 'none'
			// })
		} else {
			header[TOKENNAME] = "Bearer " + token;
		}
	}
	return new Promise((reslove, reject) => {
		uni.request({
			url: Url + url,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: (res) => {
				if (res.data.code == 0)
					reslove(res.data, res);
				else if ([401].indexOf(res.data.code) !== -1) {
					store.commit("LOGOUT");
					// uni.showToast({
					// 	title: "未登录或授权已过期请重新登录",
					// 	icon: 'none'
					// })
					reslove(res.data, res);
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					})
					reject(res.data.msg || '服务器异常');
				}

			},
			fail: (msg) => {
				reject('请求失败');
			}
		})
	});
}
const request = {};
['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt, params) => baseRequest(api, method, data, opt || {}, params)
});
export default request;